//
//  GifFuntionViewController.m
//  PersonalTool
//
//  Created by Samuel on 2/9/15.
//  Copyright (c) 2015 Samuel. All rights reserved.
//

#import "GifFuntionViewController.h"
#import "GifCollectionViewCell.h"
#import "GifLoaders.h"
#import "GifPlistList.h"
#import "UIViewController+Base.h"
#import "Animations.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "UIButton+Base.h"

#import "CreateGif.h"


@interface GifFuntionViewController ()

@end

@implementation GifFuntionViewController
{
    UIView *shadows;
    UIImageView *gifs;
    UIButton *weixinShare;
    UIButton *qqShare;
    
    UITapGestureRecognizer *hideTap;
    
    UIImagePickerController *pickerImage;
    
    NSMutableArray *gifImageList;
    NSMutableArray *gifImageNameList;
    NSMutableArray *delectRowList;
    NSMutableArray *delectName;
    
    BOOL isEdit;
    BOOL isDelecting;
    
    UIButton *rightButton;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.conllectionViews registerNib:[UINib nibWithNibName:@"GifCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"GifCollectionViewCell"];
    rightButton = [self setDefaultRightButton];
    [rightButton addTarget:self action:@selector(pictureList:) forControlEvents:UIControlEventTouchDown];
    [self setLeftButtonWithBack];
//    [leftButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchDown];
    if (gifImageList==nil) {
        gifImageList = [[NSMutableArray alloc]init];
    }
    if (gifImageNameList==nil) {
        gifImageNameList = [[NSMutableArray alloc]init];
    }
    if (delectName == nil) {
        delectName = [[NSMutableArray alloc]init];
    }
    NSMutableDictionary *gotDic = [GifPlistList getGifArray];
    gifImageList = [gotDic objectForKey:@"Data"];
    gifImageNameList = [gotDic objectForKey:@"Name"];
    if (delectRowList == nil) {
        delectRowList = [[NSMutableArray alloc]init];
    }
    [self.conllectionViews reloadData];
}
//- (void)back:(UIButton*)sender
//{
//    [self dismissViewControllerAnimated:YES completion:^{
//        ;
//    }];
//}
- (void)pictureList:(UIButton*)sender
{
    pickerImage = [[UIImagePickerController alloc] init];
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        
    }
    pickerImage.delegate = self;
    pickerImage.allowsEditing = NO;
    [self presentViewController:pickerImage animated:YES completion:^{
        ;
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    NSURL *imageRefURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    ALAssetsLibrary* assetLibrary = [[ALAssetsLibrary alloc] init];
    void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *) = ^(ALAsset *asset) {
        if (asset != nil) {
            ALAssetRepresentation *rep = [asset defaultRepresentation];
            Byte *imageBuffer = (Byte*)malloc(rep.size);
            NSUInteger bufferSize = [rep getBytes:imageBuffer fromOffset:0.0 length:rep.size error:nil];
            NSData *imageData = [NSData dataWithBytesNoCopy:imageBuffer length:bufferSize freeWhenDone:YES];
            //添加本地数组
            [gifImageList insertObject:imageData atIndex:0];
            //保存本地
            [GifPlistList saveToPlist:imageData];
            NSMutableDictionary *gotDic = [GifPlistList getGifArray];
            gifImageList = [gotDic objectForKey:@"Data"];
            gifImageNameList = [gotDic objectForKey:@"Name"];
            [pickerImage dismissViewControllerAnimated:YES completion:^{
                [self.conllectionViews reloadData];
            }];
        }
        else {
        }
    };
    
    [assetLibrary assetForURL:imageRefURL
                  resultBlock:ALAssetsLibraryAssetForURLResultBlock
                 failureBlock:^(NSError *error){
                 }];
}
 - (void)hideShadow
{
    [UIView animateWithDuration:.3 animations:^{
        shadows.alpha = 0;
        gifs.center = CGPointMake(self.view.center.x, self.view.center.y*3);
        weixinShare.alpha = 0;
        qqShare.alpha = 0;
    }completion:^(BOOL finished) {
        shadows = nil;
        gifs = nil;
        weixinShare = nil;
        qqShare = nil;
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return [gifImageList count];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    GifCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GifCollectionViewCell" forIndexPath:indexPath];
    [cell.imageViews setImage:[UIImage imageWithData:[gifImageList objectAtIndex:indexPath.row]]];
    cell.gifTime.text = [gifImageNameList objectAtIndex:indexPath.row];
    if (isDelecting==YES) {
        cell.pickDelect.selected = NO;
        if (gifImageList.count-1==indexPath.row) {
            isDelecting = NO;
        }
    }
    
    if (isEdit) {
        [cell.pickDelect setHidden:NO];
        if (cell.pickDelect.selected == NO) {
            ;
        }
        else
        {
            
        }
    }
    else
    {
        [cell.pickDelect setHidden:YES];
    }
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath;
{
    if (isEdit) {
        GifCollectionViewCell *cells = (GifCollectionViewCell*)[collectionView cellForItemAtIndexPath:indexPath];
        if (cells.pickDelect.selected == YES) {
            [delectRowList removeObject:indexPath];
            cells.pickDelect.selected = NO;
        }
        else
        {
            [delectRowList addObject:indexPath];
            cells.pickDelect.selected = YES;
        }
        
        return;
    }
    NSArray *nib = [[NSBundle mainBundle]loadNibNamed:@"GifFuntionView" owner:self options:nil];
    
    shadows = [nib objectAtIndex:0];
    gifs = [nib objectAtIndex:1];
    weixinShare = (UIButton*)[nib objectAtIndex:2];;
    qqShare = (UIButton*)[nib objectAtIndex:3];;
    
    [shadows setCenter:CGPointMake(self.view.center.x, self.view.center.y)];
    if (hideTap==nil) {
        hideTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideShadow)];
    }
    [shadows addGestureRecognizer:hideTap];
    
    [gifs setCenter:CGPointMake(self.view.center.x, self.view.center.y*3)];
    gifs.animationDuration = 3;
    gifs.animationImages = [GifLoaders getGifData:[gifImageList objectAtIndex:indexPath.row]];
    [gifs startAnimating];
    
    [weixinShare setCenter:CGPointMake(gifs.center.x/2, self.view.center.y+gifs.frame.size.height/2+30)];
    [qqShare setCenter:CGPointMake(gifs.center.x/2*3, self.view.center.y+gifs.frame.size.height/2+30)];
    weixinShare.alpha = 0;
    qqShare.alpha = 0;
    weixinShare.buttonIndexPath = indexPath;
    qqShare.buttonIndexPath = indexPath;
    [weixinShare addTarget:self action:@selector(weixinshare:) forControlEvents:UIControlEventTouchDown];
    [qqShare addTarget:self action:@selector(qqshare:) forControlEvents:UIControlEventTouchDown];
    
    [self.navigationController.view addSubview:shadows];
    [self.navigationController.view addSubview:gifs];
    [self.navigationController.view addSubview:weixinShare];
    [self.navigationController.view addSubview:qqShare];
    
    [UIView animateWithDuration:.3 animations:^{
        shadows.alpha = .5;
        
        [gifs setCenter:CGPointMake(self.view.center.x, self.view.center.y)];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:.2 animations:^{
            weixinShare.alpha = 1;
            qqShare.alpha = 1;
        }];
    }];
}



- (void)weixinshare:(UIButton*)sender
{
    NSLog(@"weixinshare     %ld",(long)sender.buttonIndexPath.row);
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //子线程中开始网络请求数据
        NSData * dataimg = [gifImageList objectAtIndex:sender.buttonIndexPath.row];
        //重新生成gif格式图片
//        NSMutableArray * gifimageArray = [GifLoaders getGifData:[gifImageList objectAtIndex:0]];
//        NSURL * urlgif = [CreateGif makeAnimatedGif:gifimageArray];
        dispatch_sync(dispatch_get_main_queue(), ^
                      {
                          if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi])
                          {
                              
                              WXEmoticonObject *wxObject = [WXEmoticonObject object];
                              wxObject.emoticonData = dataimg;
                              WXMediaMessage *message = [WXMediaMessage message];
                              message.title = @"PersonalTool For Share Gif";
                              message.description = @"个人分享工具";
                              UIImage * imgs = [UIImage imageWithData:dataimg];
                              [message setThumbImage:imgs];
                              message.mediaObject = wxObject;
                              SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
                              req.bText = NO;
                              req.message = message;
                              req.scene = WXSceneSession;
                              [WXApi sendReq:req];
                          }else {
                              UIAlertView *ale = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没装微信就别学人家点分享！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"去安装", nil];
                              ale.tag = 123;
                              [ale show];
                          }
                          
                      });
        
    });
}
- (void)qqshare:(UIButton*)sender
{
    NSLog(@"qqshare     %ld",(long)sender.buttonIndexPath.row);
}





- (IBAction)editGif:(id)sender {
    if (!isEdit) {
        isEdit = YES;
        [UIView animateWithDuration:.45 animations:^{
            self.delectGif.alpha = 1;
            self.webLink.alpha = 0;
            self.delectGif.center = self.webLink.center;
            self.webLink.center = CGPointMake(self.webLink.center.x+45, self.webLink.center.y);
        } completion:^(BOOL finished) {
            [self.editGif setTitle:@"over" forState:UIControlStateNormal];
            [self.conllectionViews reloadData];
            [rightButton removeTarget:self action:@selector(pictureList:) forControlEvents:UIControlEventTouchDown];
            [rightButton addTarget:self action:@selector(delectGifAll:) forControlEvents:UIControlEventTouchDown];

        }];
    }
    else
    {
        isEdit = NO;
        [UIView animateWithDuration:.45 animations:^{
            self.delectGif.alpha = 0;
            self.webLink.alpha = 1;
            self.delectGif.center = self.webLink.center;
            self.webLink.center = CGPointMake(self.webLink.center.x-45, self.webLink.center.y);
        } completion:^(BOOL finished) {
            [self.editGif setTitle:@"edit" forState:UIControlStateNormal];
            [self.conllectionViews reloadData];
            [rightButton removeTarget:self action:@selector(delectGifAll:) forControlEvents:UIControlEventTouchDown];
            [rightButton addTarget:self action:@selector(pictureList:) forControlEvents:UIControlEventTouchDown];
        }];
    }
    
}

- (void)delectGifAll:(id)sender
{
    [gifImageList removeAllObjects];
    [self.conllectionViews reloadData];
    [GifPlistList removeGifWith:gifImageNameList];
}
- (IBAction)delectGif:(id)sender {
    NSMutableArray *gotDellectDataLsit = [NSMutableArray array];
    for (NSIndexPath * gotRow in delectRowList) {
        [gotDellectDataLsit addObject:[gifImageList objectAtIndex:gotRow.row]];
    }

    
    for (NSData* gotDelectData in gotDellectDataLsit) {
        for (int i = 0 ; i < gifImageList.count; i++) {
            NSData* gotTargetData = [gifImageList objectAtIndex:i];
            if ([gotDelectData isEqual:gotTargetData]) {
                [gifImageList removeObject:gotTargetData];
                [delectName addObject:[gifImageNameList objectAtIndex:i]];
                
                break;
            }
        }
    }
    [GifPlistList removeGifWith:delectName];
    [delectName removeAllObjects];
    [delectRowList removeAllObjects];
    isDelecting = YES;
    [self.conllectionViews reloadData];
}











@end
